<template>
  <canvas ref="canvasRef"></canvas>
</template>

<script setup>
import {
  WebGLRenderer,
  Scene,
  PerspectiveCamera,
  MeshPhongMaterial,
  Mesh,
  DirectionalLight,
} from "three";
import { onMounted, ref } from "@vue/runtime-core";
import myBox from "./mybox";
import myCircle from "./mycircle";
import myCone from "./mycone";
import myCylinder from './mycylinder';
import myWire from './mywire';
const canvasRef = ref(null);
onMounted(() => {
  // 创建渲染器
  const renderer = new WebGLRenderer({ canvas: canvasRef.value });
  // 创建场景
  const scene = new Scene();
  //创建镜头
  const camera = new PerspectiveCamera(40, 2, 0.1, 1000);
  camera.position.z = 120;
  //   创建光源
  const light1 = new DirectionalLight(0xffffff, 1);
  light1.position.set(-1, 2, 4);
  scene.add(light1);
  const light2 = new DirectionalLight(0xffffff, 1);
  light2.position.set(1, -2, -4);
  scene.add(light2);

  const solidPrimitiveArr = []; //装所有的几何体
  solidPrimitiveArr.push(myBox,myCircle,myCone,myCylinder,myWire);
  const meshArr = []; //装所有的网格单元
  solidPrimitiveArr.forEach((item) => {
    const material = createMaterial();
    // 创建网格单元
    const mesh = new Mesh(item, material);
    meshArr.push(mesh);
  });
  let eachRow = 5; //每行显示5个
  const spread = 15;
  meshArr.forEach((mesh, index) => {
    // 计算当前网格单元所在的行
    const row = Math.floor(index / eachRow);
    const column = index % eachRow;
    mesh.position.x = (column - 2) * spread;
    mesh.position.y = (2 - row) * spread;
    scene.add(mesh); //把网格添加到场景当中
  });

//   自动旋转
  const rotate = (time) => {
    time = time * 0.001;
    const canvas = renderer.domElement; //获取到canvas
    camera.zoom = 0.5 * (canvas.clientWidth / canvas.clientHeight);
    camera.aspect = canvas.clientWidth / canvas.clientHeight; //修改宽高比例
    camera.updateProjectionMatrix(); //通知更新
    // 还有锯齿
    renderer.setSize(canvas.clientWidth, canvas.clientHeight);
    //   渲染场景和镜头
    renderer.render(scene, camera);
    meshArr.map((item) => {
      item.rotation.x = time;
      item.rotation.y = time;
    });
    window.requestAnimationFrame(rotate);
  };
  window.requestAnimationFrame(rotate); //16.7ms
});
const createMaterial = () => {
  //随机生成一种材质
  const material = new MeshPhongMaterial();
  const h = Math.floor((Math.random() * 100) / 100);
  const s = 1;
  const l = 0.5;
  material.color.setHSL(h, s, l);
  return material;
};
</script>

<style>
canvas {
  display: block;
  width: inherit;
  height: inherit;
}
</style>